from bopress.model import UserMeta
from bopress.log import Logger
from bopress.orm import SessionFactory
from sqlalchemy.sql.expression import text


def save_metas(meta_model_cls, fk_column_name, fk_column_value, meta_key, meta_value=None, value_func=None):
    """
    meta表数据保存
    :param meta_model_cls: meta数据表实体类
    :param fk_column_name: 外键列名
    :param fk_column_value: 外键查询值
    :param meta_key:
    :param meta_value:
    :param value_func: 外键赋值回调函数
    :return:
    """
    params = {fk_column_name: fk_column_value}
    s = SessionFactory.session()
    o = s.query(meta_model_cls) \
        .filter(meta_model_cls.meta_key == meta_key) \
        .filter(text("{0}=:{1}".format(fk_column_name, fk_column_name))).params(**params).one_or_none()
    try:
        if o:
            o.meta_value = meta_value
            s.commit()
        else:
            o = meta_model_cls()
            o.meta_key = meta_key
            o.meta_value = meta_value
            if value_func:
                value_func(o, fk_column_value)
            s.add(o)
            s.commit()
        return o
    except Exception as e:
        s.rollback()
        Logger.exception(e)
    return None


def get_metas(meta_model_cls, fk_column_name, fk_column_value, meta_key):
    """
    得到meta值
    :param meta_model_cls: meta数据表实体类
    :param fk_column_name: 外键列名
    :param fk_column_value: 外键查询值
    :param meta_key:
    :return:
    """
    params = {fk_column_name: fk_column_value}
    s = SessionFactory.session()
    v = s.query(meta_model_cls.meta_value) \
        .filter(meta_model_cls.meta_key == meta_key) \
        .filter(text("{0}=:{1}".format(fk_column_name, fk_column_name))).params(**params).scalar()
    return v


def delete_metas(meta_model_cls, fk_column_name, fk_column_value, meta_key):
    """
    删除meta值
    :param meta_model_cls: meta数据表实体类
    :param fk_column_name: 外键列名
    :param fk_column_value: 外键查询值
    :param meta_key:
    """
    params = {fk_column_name: fk_column_value}
    s = SessionFactory.session()
    s.query(meta_model_cls).filter(meta_model_cls.meta_key == meta_key) \
        .filter(text("{0}=:{1}".format(fk_column_name, fk_column_name))).params(**params).delete()
    s.commit()


def usermeta_value(o, v):
    o.user_id = v


def save_user_metas(user_id, meta_key, meta_value):
    def v(o):
        o.user_id = user_id

    return save_metas(UserMeta, "user_id", user_id, meta_key, meta_value, usermeta_value)


def get_user_metas(user_id, meta_key):
    return get_metas(UserMeta, "user_id", user_id, meta_key)


def delete_user_metas(user_id, meta_key):
    delete_metas(UserMeta, "user_id", user_id, meta_key)
